package com.rich.util;

import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GpsTestUtils {
	private LocationManager mLocationManager;
	private Context mContext;
	private String mProvider;
	private int mSatelliteNum;

	private List<Float> mSatelliteSignal = new ArrayList<Float>();

	public GpsTestUtils(Context context) {
		mContext = context;
	}

	public String openGps() {
		mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
		mProvider = LocationManager.GPS_PROVIDER;
		if (!mLocationManager.isProviderEnabled(mProvider)) {
			// Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), mProvider, true);
		}
		Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location == null) {
			return "Location failure";
		}
		String accuracy = String.valueOf(location.getAccuracy());
		String latitude = String.valueOf(location.getLatitude());
		String locationString = "location: " + accuracy + "*" + latitude;
		mLocationManager.addGpsStatusListener(mGpsStatusListener);
		Log.d("lrs", "location==" + location);
		return locationString;
	}

	public void closeGps() {
		if (mLocationManager.isProviderEnabled(mProvider)) {
			// Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), mProvider, false);
		}
		mLocationManager.removeGpsStatusListener(mGpsStatusListener);
	}

	private GpsStatus.Listener mGpsStatusListener = new GpsStatus.Listener() {

		@Override
		public void onGpsStatusChanged(int event) {
			GpsStatus gpsStatus = mLocationManager.getGpsStatus(null);
			updateGpsStatus(event, gpsStatus);
		}
	};

	private void updateGpsStatus(int event, GpsStatus gpsStatus) {
		if (gpsStatus == null) {
			mSatelliteNum = 0;
		} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
			Iterator<GpsSatellite> it = gpsStatus.getSatellites().iterator();
			float snr = 0;
			while (it.hasNext()) {
				if ((snr = it.next().getSnr()) >= 30) {
					mSatelliteSignal.add(snr);
					mSatelliteNum++;
				}
			}
		}
	}
}
